//
//  WBEmoticonBoard.swift
//  WBWeiBo
//
//  Created by 王斌 on 16/7/20.
//  Copyright © 2016年 王斌. All rights reserved.
//

import UIKit

//  重用标记
private let WBEmoticonCollectionViewCellIdentifier = "WBEmoticonCollectionViewCellIdentifier"


// 表情键盘
class WBEmoticonBoard: UIView {
    
    // MARK : -- 懒加载控件
    private lazy var toolBar:WBEmoticonToolBar = {
        let view = WBEmoticonToolBar(frame: CGRectZero)
        return view
    }()
    
    // 表情视图
    private lazy var emoticonCollectionView:UICollectionView = {
        
        // 布局方式
        let flowLayout = UICollectionViewFlowLayout()
        
        // 设置水平方向滚动
        flowLayout.scrollDirection = .Horizontal
        let view = UICollectionView(frame: CGRectZero,collectionViewLayout: flowLayout)
        
        //  去掉水平方向和垂直方向的滚动指示条
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        
        // 开启分页模式
        view.pagingEnabled = true
        
        // 去掉弹簧效果
        view.bounces = false
        
        view.backgroundColor = self.backgroundColor
        
        // 注册cell
        view.registerClass(WBEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: WBEmoticonCollectionViewCellIdentifier)
        
//         设置数据源代理
        view.dataSource = self
        
        return view
    }()
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    
    private func setupUI(){
        
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        addSubview(emoticonCollectionView)
        addSubview(toolBar)
        
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(self.toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.bottom.equalTo(self)
            make.trailing.equalTo(self)
            make.height.equalTo(30)
        }
        
        
        // 设置闭包
        toolBar.selectedToolBarButtonClosure = {[weak self](type:WBEmoticonToolBarButtonType) in
            
            // 定义一个将要滚动的一个NSIndexPath
            let indexPath:NSIndexPath
            
            switch type{
                
            case .Normal:
                print("normal")
                indexPath = NSIndexPath(forItem: 0, inSection: 0)
                
            case .Emoji:
                print("emoji")
                indexPath = NSIndexPath(forItem: 0, inSection: 1)
                
            case .Lxh:
                print("lxh")
                indexPath = NSIndexPath(forItem: 0, inSection: 2)
            }
            
            // 滚动到指定indexPath,不需要动画 animated:false
            self?.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
    }
    
    
    //  重写layoutSubviews,获取子控件的大小
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //  获取表情视图的布局方式
        let flowLayout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //  每项的大小等于我们表情视图的大小
        flowLayout.itemSize = emoticonCollectionView.size
        //  设置水平间距
        flowLayout.minimumInteritemSpacing = 0
        //  设置垂直间距
        flowLayout.minimumLineSpacing = 0
    
    }
    
    
}

extension WBEmoticonBoard:UICollectionViewDataSource{
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return WBEmoticonTools.shareTools.allEmoticonArray.count
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return WBEmoticonTools.shareTools.allEmoticonArray[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBEmoticonCollectionViewCellIdentifier, forIndexPath: indexPath) as! WBEmoticonCollectionViewCell

        //  设置模型
        cell.emoticons = WBEmoticonTools.shareTools.allEmoticonArray[indexPath.section][indexPath.item]
        return cell
    }
    
    
    
    func scrollViewDidScroll(scrollView:UIScrollView){
        
        //  1. 获取屏幕显示的cell,只是能够返回当前显示cell,但是不会给我frame.x 进行排序
        let cells = emoticonCollectionView.visibleCells().sort { (firstCell, secondCell) -> Bool in
            
            // 通过sort进行x坐标从小到大的排序
            return firstCell.x < secondCell.x
        }
        
        
        //  2. 判断哪个cell显示的多
        if cells.count == 2 {
            
            // 第一个cell
            let firstCell = cells.first!
            
            // 第二个cell
            let secondCell = cells.last!
            
            // 计算第一个cell的x坐标与水平偏移量的差值
            let firstCellContentOffSetX = abs(firstCell.x - scrollView.contentOffset.x)
            
            //  计算第二个cell的x坐标与水平偏移量的差值
            let secondCellContentOffSetX = secondCell.x - scrollView.contentOffset.x
        
        
            // 比较差值,通过规律可以得知,哪个差值小,哪个cell显示就越多
            let cell:UICollectionViewCell
            
            if firstCellContentOffSetX < secondCellContentOffSetX{
                
                // 第一个cell显示多
                cell = firstCell
            }else{
                
                // 第二个显示多
                cell = secondCell
            }
        
        
            //  3. 通过cell获取对应的indexPath
            let indexPath = emoticonCollectionView.indexPathForCell(cell)!
            
            //  4. 通过indexPath获取对应这个section
            let section = indexPath.section
            
            //  5. toolbar根据section让其指定的按钮选中
            toolBar.selectedButtonWidthSection(section)
        
        }
    }
   
}


